$.get('/static/admin/lib/cropper/cropper.js?v=1');
layui.link('/static/admin/lib/cropper/cropper.css');
layui.link('/static/admin/css/js/images.css');
layui.define(['jquery', 'layer','upload','form'], function (exports) {
    
    var getUploadHtml = function(){
  return  '<div class="layui-form-item" style="margin-top:2px;margin-bottom:2px; margin-left:0px" >'
        +'    <div class="layui-btn-group" id="JF_btn_main">'
        +'        <button type="button" class="layui-btn JF_btn_selectFile" crop-event="change" >重选图片</button>'
        +'        <button type="button" class="layui-btn" crop-event="rotate" data-option="90" >正旋转90度</button>'
        +'        <button type="button" class="layui-btn" crop-event="rotate" data-option="-90" >逆旋转90度</button>'
        +'        <button type="button" class="layui-btn" crop-event="reset" >重置图片</button>'       
        +'        <button type="button" class="layui-btn layui-btn-normal" crop-event="saveData" >保存结果</button>'
        +'        <button type="button" class="layui-btn layui-btn-primary" crop-event="close" >取消</button>'
        +'    </div>'
        +' </div>'   
        +'<div id="JF_drag_main" class="layui-upload-drag JF_btn_selectFile" style="width: 520px;height: 300px;margin-top: 10px;">'
        +'    <i class="layui-icon"></i>'
        +'    <p>点击上传，或将文件拖拽到此处</p>'
        +'</div>'     
        +'<div id="JF_cropper_main" style="display: none;"  >'
        +'    <div class="layui-row" >'
        +'        <div class="layui-col-md9 layui-col-sm9 layui-col-xs12" >'
        +'            <img id="JF_cropper_img" style="width: 100%;max-height:560px" src="" />'
        +'        </div>'
        +'        <div class="layui-col-md3 layui-col-sm3 layui-hide-xs"  id="JF_cropper_preview" style="padding: 0px 10px;">'
        +'           <div class="p-preview JF_cropper_previewOne" style="width: 100%; height: 100px;overflow: hidden"></div>'
        +'        <div class="p-preview" style="width: 100%; margin-top: 40px;font-size: 11px;color: #666;">双击右边图片可切换拖动图片或选择框<br/>滚动鼠标可以放大缩小图片</div>'
        +'    </div>'
        +'</div>'        
    }
        
    var getHtml = function(type){
       var html = '<div class="layui-tab layui-tab-brief">' 
            +'<ul class="layui-tab-title" id="JF_title">'
            +'    <li data-show="my" class="layui-this JF_T_my" >我的图片</li>'
            +'    <li data-show="upload" class="JF_T_upload" >上传图片</li>'
            +'    <li data-show="server" class="JF_T_server">图片库</li>'
            +'</ul>'
       +'<div class="layui-tab-content" id="JF_content" >'
       +' <div class="layui-tab-item JF_C_my"></div>'
       +' <div class="layui-tab-item JF_C_upload">自定义上传图片'       
       +' </div>'
       +' <div class="layui-tab-item JF_C_server"></div>'
       +'</div></div>';
       return html;
    }
    
    // 各种事件处理
    var imageEvents = function(mainElem,sys){
        //关闭按钮
        var closeView = function(){
            $(mainElem).find('img').cropper('destroy');
            layer.closeAll();
        }
        //-------------------------------
        // 上传图片
        var uploadAction = function(){
            var upconfig = {
                lockUp : false, // 上传过程中加锁
                imageObject: '', // 存放图片的img对象
                croConfig  : '', // 剪切参数
                uploadInst : '',  // upload 上传图片对象
                uploadData : {'width':0,'height':0,'imgx':0,'imgy':0}       // 剪切数据
            }
            
            var uploadHtml = getUploadHtml();
            mainElem.find('.JF_C_upload').html(uploadHtml);
            var JF_drag_mainElem = $(mainElem).find('#JF_drag_main'),
            JF_cropper_mainElem = $(mainElem).find('#JF_cropper_main');
            
            //按钮操作            
            $(mainElem).find('#JF_btn_main .layui-btn').on('click',function(){
                var btnEvent = $(this).attr("crop-event");
                console.log(btnEvent);
                if( btnEvent  === 'close'){ // 关闭
                    closeView();       
                }else if( btnEvent  === 'saveData' ){
                    if(typeof upconfig.imageObject.cropper == 'undefined') return false;
                    if( upconfig.lockUp === true ) return false;
                    upconfig.lockUp = true;                      
                    var cronData = upconfig.imageObject.cropper('getData');
                    upconfig.uploadInst.config.data = {
                        'width' : cronData.width,
                        'height': cronData.height,
                        'imgx'  : cronData.x,
                        'imgy'  : cronData.y,
                        'rotate': cronData.rotate,
                        'type'  : sys.data.type
                    };
                    upconfig.uploadInst.upload();
                }else if( btnEvent === 'reset'){   // 重置选择
                    upconfig.imageObject.cropper('reset');
                }else if (btnEvent === 'rotate') {
                    var option = $(this).attr('data-option');
                    upconfig.imageObject.cropper('rotate', option);
                }
            });
            // 剪切图片处理
            var cropperDeal = function(imageObject){                
                upconfig.lockUp = false;
                upconfig.croConfig = {
                    aspectRatio: sys.saveW / sys.saveH ,
                    preview: $(mainElem).find(".JF_cropper_previewOne"),
                    strict:true,
                    autoCropArea:1, //自动剪裁的区域大小
                    crop: function(e) {
                    },            
                    built: function () {
                        console.log('built');
                    }
                };
                imageObject.cropper(upconfig.croConfig);
            }
            
            //绑定触发选择图片按钮 
            upconfig.uploadInst = layui.upload.render({
                elem : '.JF_btn_selectFile', //绑定元素
                url  : sys.url, //上传接口
                data : sys.data,    
                auto : false, // 取消选择文件后自动上传
                //bindAction　: '#JS_c_bindAction', // 绑定触发上传的按钮                    
                choose : function (obj){ // 选择文件之后处理  
                    obj.preview(function(index, file, result){
                        JF_drag_mainElem.hide();
                        JF_cropper_mainElem.show();
                        upconfig.imageObject = $(mainElem).find('#JF_cropper_img');
                        upconfig.imageObject.cropper('destroy');
                        upconfig.imageObject.attr('src',result);
                        cropperDeal(upconfig.imageObject);
                        setTimeout(function(){ // 重新定位
                            var height  =  JF_cropper_mainElem.height();
                            var bottomH = sys.boxhight - 120 - height;
                            if( bottomH > 10 ) JF_cropper_mainElem.css({"margin-top":bottomH/2});
                        },100);
                        
                    });
                },
                before: function(obj){ //上传文件之前的回调
                    //$.extend(c.uploadInst.config.data,c.uploadData);
                },
                done:function(ret){
                    closeView();
                    ret.data = new Array( ret.data ); // 修正为多张图片模式
                    sys.done(ret);
                },
                error:function(){
                    closeView();
                    sys.error(ret);
                }
            });
        }
        
        
        
        // 图库
        var imgConfig = {
            album : '', // 相册列表数据 
            image : new Array(), // 已经选择的图片 
            datamy: {id:0}, //{id:11 ,albumid:{page,data}}
            dataserver : {id:0},
        };
        var showServerImage = function(contentElem,show){
            var getPost = function(url,data,backFunc){
                $.get(url,data,function(data){
                    if( data.code == 1 ){
                        if( typeof backFunc == 'function' ) backFunc(data.data);
                    }else{
                        layer.msg(data.msg);
                    }
                },'json');
            }
            
            // 展示相册的下拉框
            var ShowAblumSelect = function(){
                var albumList = imgConfig.album[show];
                var htmlSelect=  '';
                if( albumList.length > 1 ){
                    htmlSelect = '<div class="layui-input-inline" style="width: 100px;">'
                    +'  <select name="JF_ablum" lay-filter="JF_ablum" >'
                    +'    <option value="0">请选择相册</option>';
                    $.each(albumList,function(key,val){                        
                        var tCss = val['id'] == imgConfig['data'+show]['id'] ? 'selected':'';
                        htmlSelect += '<option '+tCss+' value="'+val['id']+'">'+val['name']+'</option>';
                    });
                    htmlSelect += '  </select></div>';
                }
                var topHtml = '<div class="layui-form layui-form-pane ef-images-select-top" >'
                    + htmlSelect
                   // +'<div class="ef-images-box ef-images-preshow" >'
                   // +'  <img  src="http://img.elite.com/uploads/editor/2019/06/27/m1/5d1421e645ebe.png">'
                   // +'<i title="删除" class="layui-icon layui-icon-close ef-images-check"></i>  '
                   // +'</div>'
                   // +'<span class="JF_showNum" style="padding-left:4px">可选1张</span>'
                    +'<div class="layui-btn-group ef-images-preshow-btn" style="float: right;">'
                    +'    <button data-event="save" class="layui-btn layui-btn-normal JF_clickEvent" >保存结果</button>' 
                    +'    <button data-event="close" class="layui-btn layui-btn-primary JF_clickEvent" >取消</button>' 
                    +'</div>'
                +'</div>';
                contentElem.find('.ef-images-select-top').remove();
                contentElem.prepend(topHtml);
                showSelectImg();
                layui.form.render('select');
                
                layui.form.on('select(JF_ablum)', function(data){
                    var albumid = data.value;
                    imgConfig['data'+show]['id'] = albumid; // 保存当前选中的ID
                    if( typeof imgConfig['data'+show][albumid] == 'undefined'){
                        imgConfig['data'+show][albumid] = {page:1,data:''};
                        getImageAndShow(1);
                    }else{
                        // 隐藏其他相册的数据 并且展示当前的数据
                        //console.log(imgConfig['data'+show][albumid]);
                        //console.log(imgConfig['data'+show][albumid]['data']);
                        showImageList(imgConfig['data'+show][albumid]['data']);
                    }
                }); 
            }
            
            // 读取某个相册的数据并展示在页面上
            var getImageAndShow = function(action){
                var albumid = imgConfig['data'+show]['id']; //相册ID               
                if( action == 'more' ){
                    imgConfig['data'+show][albumid]['page'] ++;
                }
                var page = imgConfig['data'+show][albumid]['page'];
                var layerIndex = layui.layer.load(0);
                getPost(sys.urlimg,{'showtag':show,'albumid':albumid,'page':page},function(data){
                    layui.layer.close(layerIndex);
                    if( imgConfig['data'+show][albumid]['data'] == '' ){
                        imgConfig['data'+show][albumid]['data'] = data.list;
                    }else{
                        if( data.list.length > 0 ){
                            imgConfig['data'+show][albumid]['data'].push.apply(imgConfig['data'+show][albumid]['data'],data.list);
                        }
                    }
                    //console.log(albumid);
                    if( data.list.length < 1 ){
                        layer.msg('该分类下的图片已经全部加载了...');
                    }
                    showImageList(imgConfig['data'+show][albumid]['data'],data.list.length);
                    //console.log( imgConfig['data'+show][albumid]);
                });
            }
            
            // 保存已经选中的图片 并显示
            var showSelectImg = function(action,id,pic){
                if( action == 'add' || action == 'del' ){
                    var save = {id : id, pic:pic};
                    $.each(imgConfig.image,function(k,v){
                        if( v.id == id ){
                            imgConfig.image.splice(k,1); // 删除
                            return false;
                        } 
                    });
                    if( action == 'add' ){
                        if( sys.num < 2 ){
                            imgConfig.image = new Array( save );
                        }else{
                            imgConfig.image.push(save);
                        }
                    }
                }                
                
                //组织已选择的图片展示
                var getPreShowImgHtml = function(){
                    var preShow = '';
                    $.each(imgConfig.image,function(k,v){
                        preShow += '<div data-id="'+v.id+'" class="ef-images-box ef-images-preshow" >'
                        +'  <img  src="'+v.pic+'">'
                        +'<i style="display:none;" title="删除" class="layui-icon layui-icon-close ef-images-check"></i>  '
                        +'</div>';
                    });
                    var lastNum = sys.num - imgConfig.image.length;
                    var txt = lastNum > 0 ? '可选'+lastNum+'张' : '完成';
                    preShow +='<span class="JF_showNum" style="padding-left:4px">'+txt+'</span>';
                    return preShow;
                }
                
                var html = getPreShowImgHtml(); //ef-images-select-top
                if( imgConfig.image.length > 5 ){
                    mainElem.find('.ef-images-select-top').css({'height': '100px'});
                }else{
                    mainElem.find('.ef-images-select-top').css({'height': '40px'});
                }
                mainElem.find('.ef-images-select-top .ef-images-preshow').remove();
                mainElem.find('.ef-images-select-top .JF_showNum').remove();
                mainElem.find('.ef-images-select-top .ef-images-preshow-btn').before(html);   
                             
                mainElem.find('.ef-images-preshow').on('mouseover',function(){
                    $(this).find('.ef-images-check').show();
                });
                mainElem.find('.ef-images-preshow').on('mouseout',function(){
                    $(this).find('.ef-images-check').hide();
                });
                mainElem.find('.ef-images-check').on('click',function(){
                    var id = $(this).parents('.ef-images-preshow').data('id');
                    if( mainElem.find('div.ef_id_'+id +' .JF_del').length > 0 ){
                        mainElem.find('div.ef_id_'+id +' .JF_del').click();
                    }else{
                        showSelectImg('del',id,'');
                    }                    
                });
            }
            
            // 显示图片
            var showImageList = function(list,more){   
                var imgList = '';
                var dealSelect = function(id){
                    var ret = {
                        icon : 'style="display:none"',
                        add  : '',
                        del  : 'style="display:none"',
                        border : ''
                    }
                    if( sys.num < 2 ) return ret; // 只需选择一张时不做选中标签
                    $.each(imgConfig.image,function(k,v){
                        if( v.id == id ){
                            console.log( '选中' );
                            console.log(v);
                            ret = {
                                icon : '',
                                add  : 'style="display:none"',
                                del  : '',
                                border : 'border-color:#009688'
                            }
                            return false;
                        }
                    });
                    return ret;
                }
                $.each(list,function(key,val){
                    var tCss = dealSelect(val.id);
                    imgList += '<div class="ef-images ef_id_'+val['id']+' ef_pid_'+val['albumid']+'" data-id="'+val['id']+'" data-pic="'+val['picurl']+'">'
                        +'<div class="ef-images-box" style="'+tCss.border+'">'
                        +'  <img  src="'+val['picurl']+'">'
                        +'<i '+tCss.icon+' class="layui-icon layui-icon-vercode ef-images-check"></i>  '
                        +'</div>'
                        +'<div class="ef-images-txt">'
                        +'  <span style="padding:10px;display:inline-block;width: 120px;word-wrap: break-word;">'+val['picname']+'</span>'
                        +'  <div class="ef-images-btn">'
                        +'    <button '+tCss.del+' data-event="del" class="layui-btn layui-btn-warm JF_clickEvent JF_del" >取消</button>' 
                        +'    <button '+tCss.add+' data-event="add" class="layui-btn JF_clickEvent JF_add" >选择</button>' 
                        +'  </div>'
                        +'</div>'
                        +'</div>';
                });
                if( more == 0 ){
                    imgList += '<div data-event="more" class="ef-images-more"><a href="javascript:;" class="layui-btn layui-btn-primary">该分类图片已全部在这里了</a></div>'
                }else{
                    imgList += '<div data-event="more" class="ef-images-more JF_clickEvent"><a href="javascript:;" class="layui-btn layui-btn-primary">点击加载更多</a></div>'
                }                
                contentElem.find('.ef-images').remove();
                contentElem.find('.ef-images-more').remove();
                contentElem.append(imgList);
                bindAblumAction();
            }
            // 注册事件
            var bindAblumAction = function(){
                //console.log('注册点击事件');
                contentElem.find('.ef-images').on('mouseover',function(){
                    $(this).find('.ef-images-txt').show();
                });
                contentElem.find('.ef-images').on('mouseout',function(){
                    $(this).find('.ef-images-txt').hide();
                });
                contentElem.find('.JF_clickEvent').on('click',function(){
                    var event = $(this).data('event');
                    var imageElem = $(this).parents('.ef-images');
                    //console.log( event );
                    if( event == 'add' || event == 'del'  ){
                        if( sys.num > 1 ){
                            if( event == 'add' ){   
                                // 判断选择的图片数量
                                //console.log( imgConfig.image.length );
                                if( sys.num < imgConfig.image.length + 1 ){
                                    layui.layer.msg('最多可以选择'+sys.num+'张,您已选'+sys.num+'张,请点击"保存结果"按钮完成图片选择');
                                    return false;
                                }                            
                                imageElem.find('.ef-images-check').show();
                                imageElem.find('button.JF_del').show();
                                imageElem.find('.ef-images-box').css({'border-color': '#009688'});
                                
                            }else{
                                imageElem.find('.ef-images-check').hide();
                                imageElem.find('button.JF_add').show();
                                imageElem.find('.ef-images-box').css({'border-color': '#eee'});
                            }
                            $(this).hide();
                        }else if ( imgConfig.image.length > 0 && event == 'add' ){
                            layui.layer.msg('只能选1张,该图片已经替换之前选的图片,请点击"保存结果"按钮完成图片选择');
                        }                        
                        showSelectImg(event,imageElem.data('id'),imageElem.data('pic'));                      
                    }else if(event == 'more'){
                        getImageAndShow('more');
                    }else if(event == 'close'){
                        closeView();
                    }else if(event == 'save'){
                        
                        var retData = { code : 0, data : new Array(), msg:'未选择图片'};
                        if( imgConfig.image.length > 0 ){
                            retData.code = 1;
                            retData.msg  = 'OK';
                            $.each(imgConfig.image,function(k,v){
                                retData.data.push(v.pic);
                            });
                        }else{
                            layui.layer.msg('请至少选择一张图片');
                            return false;
                        }
                        closeView();
                        sys.done(retData);   
                    }
                });
            }
            
            // 初始化事件
            if( imgConfig.album == '' ){
                getPost(sys.urlalbum,{'showtag':show,'type':sys.data.type},function(data){
                    imgConfig.album = { my:data.my ,server:data.server };
                    //console.log( imgConfig );
                    
                    imgConfig['data'+show]['id'] = data.albumid; // 保存当前的相册ID
                    imgConfig['data'+show][data.albumid] = {page:1,data:data.img.list};
                    
                    ShowAblumSelect();
                    showImageList(data.img.list);
                });
            }else{
                var albumid = imgConfig['data'+show]['id'];
                if( ( typeof imgConfig['data'+show][albumid] == 'undefined') ){  
                   // console.log( '标签首次加载');
                    if( imgConfig.album[show].length > 0 ){
                        albumid = imgConfig.album[show][0]['id'];
                        imgConfig['data'+show]['id'] = albumid;
                        imgConfig['data'+show][albumid] = {page:1,data:''};
                        getImageAndShow(1);
                    }
                    ShowAblumSelect();
                }else{
                    ShowAblumSelect();
                    bindAblumAction();
                }
                //showImageList();
            }
            
        }
        
        
        // -------------------------------
        mainElem.find('#JF_title li').on('click',function(){
            var show = $(this).data('show'),
            JF_contentElem = mainElem.find('.JF_C_'+show);
            $(this).addClass('layui-this').siblings().removeClass('layui-this');
            JF_contentElem.addClass('layui-show').siblings().removeClass('layui-show');
            if( show == 'upload' ){
                uploadAction();
            }else{
                showServerImage(JF_contentElem,show);
            }
        });
        var init = function(){
            console.log('开始');
            mainElem.find('.JF_T_'+sys.show).click();
            console.log('结束');
           // $('#JF_btn_selectFile').click();
        }
        init();
        
    }
    
    
    // 对外调用方法
    var images = {        
        render: function (e){
            var sys = {
                elem : '#JS_upload_btn', // 绑定页面的操作按钮
                show  : 'my',// upload 选择本地图片进行剪切上传 ，server 读取服务器的公共图库 my 读取自己上传记录图库
                saveH : 200, // 剪切后保存图片的 高度
                saveW : 200, // 剪切后保存图片的 宽度
                url   : '/sys/Upload/image', // 上传接口
                urlalbum : '/sys/Images/ajaxalbum', // 读取相册的接口
                urlimg   : '/sys/Images/ajaximg', // 读取相册图片的接口
                num   : 1,  // 选择的图片数量
                data  : {'type':'default'}, // editor default
                blob  : false,
                done  : function(){},  //上传成功后回调        
                error : function(msg){
                    layer.open({
                        skin:'layui-layer-admin',
                        shade: 0,
                        closeBtn:0,
                        offset: 't',
                        anim: 3,
                        time: 3000,
                        title: '信息',
                        content: msg
                    });            
                } //上传失败的回调
            }
            
            $win = $(window);
            var winHight = $win.height();
            var maxHight = 700,offset = 10;
            if( winHight < 700 ) maxHight = winHight-20;
            if( winHight > 700 ) offset = (winHight - 700 )/2;
            sys.boxhight = maxHight; // 打开窗口的高度
            //console.log(sys);
            $.extend(sys,e);
            sys.data.type = sys.type;
            //添加页面按钮的点击事件            
            $(JS_upload_btn).on('click',function(){
                layui.layer.open({
                    scrollbar: true,
                    skin:'layui-layer-admin',//layui-layer-lan', // layui-layer-molv
                    closeBtn:0,
                   // title: "添加图片",
                    title: false, // 不显示标题
                    //closeBtn: false,
                    offset: offset+'px',
                    type: 1,
                    content: '<div id="JF_uploadimg_main"></div>',//'aaaa',
                    area: ['620px',maxHight+'px'],
                    success: function () {
                        console.log('打开图片管理窗口');
                        var html = getHtml(sys.show);   
                        var mainElem = $(html);
                        $('#JF_uploadimg_main').html(mainElem);
                        var upload = new imageEvents(mainElem,sys);
                    },
                    cancel: function (index) {   
                        console.log('关闭');
                        //closeView();
                    }
                });
            });
        }
    } 
    
    exports('images', images);
});